import { useState, useEffect } from "react";
import { connect } from "react-redux";
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { formatTimeString, formatActicityType, formatNumTo2 } from '@/utils';
// css
import styles from '@/styles/CommonOrder.module.scss';
// 
import { setRealPayPrice } from '@/store/actions/cart';

// 计算折扣券，满足的商品才能使用
function caclateCoupon (cartList, item){
    const { rebatePrice, rebateMethod } = item;
    let _rebatePrice = 0;
    if(rebateMethod == 2){
        const discountCoupons = [];
        cartList.forEach(part => {
            const { goodsCartActivityListDTO } = part;
            goodsCartActivityListDTO.forEach(dto => {
                const { userCanUseCouponDTOList } = dto;
                for (let index = 0; index < userCanUseCouponDTOList.length; index++) {
                    const coupon = userCanUseCouponDTOList[index];
                    if(coupon.couponId == item.couponId){
                        discountCoupons.push(dto);
                        break
                    }
                }
            })
        });
        const discountRatio = rebatePrice/(rebatePrice >= 10 ? 100 : 10);
        discountCoupons.forEach(c => {
            _rebatePrice += c.salePrice * (1 - discountRatio);
        });
    }else{
        _rebatePrice = rebatePrice;
    }
    return _rebatePrice
}

// 优惠券
const Coupon = ({ _setRealPayPrice, cart: { cartList, totalPrice, reducePrice } }) => {

    const [collapse, setCollapse] = useState(false);
    const [haveCoupon, setHaveCoupon] = useState(false);
    const [coupons, setCoupons] = useState([]);
    const [uCoupons, setUCoupons] = useState([]);
    const [canUseCoupon, setCanUseCoupon] = useState(true);

    // 获取优惠券
    useEffect(() => {
        const dataList = JSON.parse(sessionStorage.getItem('cartList') || '[]');
        let _coupon = [], _total = 0;
        let _canUseCoupon = true;
        dataList.forEach(item => {
            const { activityBaseId, reducePrice, goodsCartActivityListDTO } = item;  
            if(activityBaseId && reducePrice){
                _canUseCoupon = false;
                setCanUseCoupon(false);
            }
            goodsCartActivityListDTO.forEach(dto => {
                const { userCanUseCouponDTOList, amount, salePrice } = dto;
                _total += amount*salePrice;
                userCanUseCouponDTOList.forEach(coupon => {
                    const { couponId, rebateMethod, rebatePrice } = coupon,
                          isRepeat = _coupon.some(c => {
                            return c.couponId === couponId;
                          });
                    coupon.discountPrice = rebateMethod == 2 ? `${rebatePrice/(rebatePrice>=10 ? 10 : 1)}折` : "";
                    !isRepeat && _coupon.push(coupon);
                });
            })
        });
        if(_coupon.length){
            setHaveCoupon(true);
        }
        _canUseCoupon ? setCoupons([..._coupon]) : setUCoupons([..._coupon]);
        _setRealPayPrice({
            totalPrice: formatNumTo2(_total),
            realPayPrice: formatNumTo2(_total),
            reducePrice: reducePrice
        });
    }, []);

    // 选择优惠券
    function useCoupon (data){
        let _rebatePrice = caclateCoupon(cartList, data);
        coupons.forEach(c => {
            if((data.couponId && data.couponId == c.couponId) || (data.activityBaseId && data.activityBaseId == c.activityBaseId)){
                c.chosen = !c.chosen;
                if(c.chosen){
                    _setRealPayPrice({
                        totalPrice: formatNumTo2(totalPrice),
                        realPayPrice: formatNumTo2(totalPrice-_rebatePrice), 
                        reducePrice: formatNumTo2(_rebatePrice)
                    });
                    sessionStorage.setItem('useCoupon', JSON.stringify(data));
                }else{
                    _setRealPayPrice({
                        totalPrice: formatNumTo2(totalPrice),
                        realPayPrice: formatNumTo2(totalPrice-(reducePrice-_rebatePrice)), 
                        reducePrice: formatNumTo2(reducePrice-_rebatePrice)
                    });
                    sessionStorage.removeItem('useCoupon');
                }
            }else{
                c.chosen = false;
            }
        });
        setCoupons([...coupons]);
    }

    // Component
    const PriceInfo = (
        <p className={styles['price-total-box']}>
            <span>费用合计：<em>￥</em><strong>{totalPrice}</strong></span>
            <span>优惠金额：<em>￥</em><strong>{reducePrice}</strong></span>
        </p>
    );

    if(!haveCoupon){
        return <div className={styles['price-total-wrap']}>{ PriceInfo }</div>
    }
    // 价格
    const couponPrice = (item) => {
        const { couponType } = item;
        return (
            <>
                <p className={styles['price']}>￥<em>{item.discountPrice || item.rebatePrice}</em></p>
                { couponType == 3 ? <p>无使用门槛</p> : ''}
                { couponType == 2 ? <p>满{item.satisfyPrice}可用</p> : ''}
                { couponType == 1 ? <p>体验券</p> : ''}
                { (couponType != 1 && couponType != 2 && couponType != 3) ? <p>{formatActicityType(item.algorithms)}</p> : ''}
            </>
        )
    }
    // 优惠券信息
    const couponInfo = (item) => {
        const { validityType } = item;
        return (
            <>
                <p className={styles['name']}>{item.name || item.activityName}</p>
                <p className={styles['time']}>
                    <span>有效期：</span>
                    {
                        validityType == 1 
                        ? `${formatTimeString(item.startTime)}至${formatTimeString(item.endTime)}`
                        : `领取${item.validityDay || 0}天内有效`
                    }
                </p>
                <p className={styles['desc']}><span>使用规则：</span>{item.remark || '--'}</p>
            </>
        )
    }

    return (
        <div className={[styles['coupon-box'], styles['coupon-cart'], collapse ? styles['collapse'] : ''].join(' ')}>
            <h3 className={styles['title']}>优惠券
                <span>说明：1）优惠活动与优惠券不可同时使用；2）只能使用一张优惠券</span>
                <span onClick={() => { setCollapse(!collapse) }}>
                    { collapse ? <DownOutlined title="展开" /> : <UpOutlined title="收起" /> }
                </span>
            </h3>
            <div className={styles['coupon-list']}>
                {
                    canUseCoupon
                    ? coupons.map(item => {
                        return (
                            <div className={[styles['item'], item.chosen && styles['chosen']].join(' ')}
                                 key={item.couponId || item.activityBaseId}
                                 onClick={() => { useCoupon(item) }}
                            >
                                <div className={styles['left']}>{couponPrice(item)}</div>
                                <div className={styles['center']}>{couponInfo(item)}</div>
                                <div className={styles['right']}><span></span></div>
                            </div>
                        )
                    })
                    : uCoupons.map((item, index) => {
                        return (
                            <div className={[styles['item'], styles['disabled']].join(' ')} key={index}>
                                <div className={styles['left']}>{couponPrice(item)}</div>
                                <div className={styles['center']}>{couponInfo(item)}</div>
                            </div>
                        )
                    })
                }
                { PriceInfo }
            </div>
        </div>
    )
};

const mapStateToProps = state => {
    return {
        cart: state.cart
    }
}
const mapDispatchToProps = dispatch => {
    return {
        _setRealPayPrice: v => dispatch(setRealPayPrice(v))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Coupon)